package red.mlz.excelservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class DynamicExcelListener extends AnalysisEventListener<Map<Integer, String>> {
    private static final Logger LOGGER = LoggerFactory.getLogger(DynamicExcelListener.class);

    private final List<Map<String, String>> data = new ArrayList<>();
    private Map<Integer, String> headers = new LinkedHashMap<>();
    private final int headerRow;
    private boolean headerProcessed = false;

    public DynamicExcelListener(int headerRow) {
        this.headerRow = headerRow;
    }

    @Override
    public void invoke(Map<Integer, String> rowData, AnalysisContext context) {
        int currentRow = context.readRowHolder().getRowIndex();
        LOGGER.info("当前行号：{}", currentRow);
        LOGGER.info("原始行数据：{}", rowData);

        // 处理表头
        if (currentRow == headerRow) {
            LOGGER.info("捕获表头：{}", rowData);
            headers.putAll(rowData);
            headerProcessed = true;
            return;
        }

        // 处理数据行
        if (headerProcessed) {
            Map<String, String> converted = new LinkedHashMap<>();
            headers.forEach((index, title) -> {
                String value = rowData.getOrDefault(index, "");
                LOGGER.info("映射字段：{} → {}", title, value);
                converted.put(title, value);
            });
            data.add(converted);
            LOGGER.info("当前映射结果：{}", converted);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        LOGGER.info("所有数据处理完成，总记录数：{}", data.size());
    }

    public List<Map<String, String>> getResult() {
        return data;
    }
}